package com.leoman.user.service.impl;

import com.leoman.common.controller.common.CommonController;
import com.leoman.common.service.impl.GenericManagerImpl;
import com.leoman.creator.dao.CreatorDao;
import com.leoman.creator.entity.Creator;
import com.leoman.creatordynamic.dao.CreatorDynamicDao;
import com.leoman.creatordynamic.entity.CreatorDynamic;
import com.leoman.entity.Constant;
import com.leoman.entity.FileBo;
import com.leoman.indexapi.service.UserTaskApiService;
import com.leoman.sensitivewords.dao.SensitiveWordsDao;
import com.leoman.sensitivewords.entity.SensitiveWords;
import com.leoman.user.dao.UserInfoDao;
import com.leoman.user.dao.UserLoginDao;
import com.leoman.user.entity.UserInfo;
import com.leoman.user.entity.UserLogin;
import com.leoman.user.service.UserService;
import com.leoman.utils.DateUtils;
import com.leoman.utils.FileUtil;
import com.leoman.work.dao.WorkCreatorDao;
import com.leoman.work.entity.WorkCreator;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 蔡琦 on 2016/6/14 0014.
 */
@Service
public class UserServiceImpl extends GenericManagerImpl<UserInfo, UserInfoDao> implements UserService {

    @Autowired
    private UserInfoDao userInfoDao;

    @Autowired
    private CreatorDao creatorDao;

    @Autowired
    private UserLoginDao userLoginDao;

    @Autowired
    private SensitiveWordsDao sensitiveWordsDao;

    @Autowired
    private UserTaskApiService userTaskApiService;

    @Autowired
    private CreatorDynamicDao creatorDynamicDao;

    @Autowired
    private WorkCreatorDao workCreatorDao;

    @Override
    public Page<UserInfo> page(final String mobile, final String nickname, final Integer gender, final Integer status, final Integer type,
                               final String startDate, final String endDate, final Integer isCreator, Integer sort, Integer pageNum, Integer pageSize) {
        PageRequest pageRequest = null;
        // 普通用户
        if (isCreator != null && isCreator == 0) {
            if (sort == null) {
                // 默认按馒头数倒序
                pageRequest = new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "coin");
            } else if (sort == 1) {
                // 按等级倒序
                pageRequest = new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "level");
            } else if (sort == 2) {
                // 按等级正序
                pageRequest = new PageRequest(pageNum - 1, pageSize, Sort.Direction.ASC, "level");
            } else if (sort == 3) {
                // 按馒头数正序
                pageRequest = new PageRequest(pageNum - 1, pageSize, Sort.Direction.ASC, "coin");
            }
        } else {
            // 主创用户按id倒序
            pageRequest = new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "id");
        }

        Page<UserInfo> page = userInfoDao.findAll(new Specification<UserInfo>() {
            @Override
            public Predicate toPredicate(Root<UserInfo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate result = null;
                List<Predicate> predicateList = new ArrayList<>();
                if (StringUtils.isNotEmpty(mobile)) {
                    Predicate pre = cb.like(root.get("mobile").as(String.class), "%" + mobile + "%");
                    predicateList.add(pre);
                }
                if (StringUtils.isNotEmpty(nickname)) {
                    Predicate pre = cb.like(root.get("nickname").as(String.class), "%" + nickname + "%");
                    predicateList.add(pre);
                }
                if (gender != null) {
                    Predicate pre = cb.equal(root.get("gender").as(Integer.class), gender);
                    predicateList.add(pre);
                }
                if (status != null) {
                    Predicate pre = cb.equal(root.get("status").as(Integer.class), status);
                    predicateList.add(pre);
                }
                if (type != null) {
                    Predicate pre = cb.equal(root.get("type").as(Integer.class), type);
                    predicateList.add(pre);
                }
                if (isCreator != null) {
                    Predicate pre = cb.notEqual(root.get("isCreator").as(Integer.class), Constant.IF_CREATOR_NO);
                    predicateList.add(pre);
                } else {
                    Predicate pre = cb.equal(root.get("isCreator").as(Integer.class), Constant.IF_CREATOR_NO);
                    predicateList.add(pre);
                }

                Predicate pre1 = cb.notEqual(root.get("nickname").as(String.class), Constant.YULEJUN);
                predicateList.add(pre1);

                if (StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate)) {

                    try {
                        Predicate pre2 = cb.ge(root.get("createDate").as(Long.class), DateUtils.stringToLong(startDate, "yyyy-MM-dd hh:mm:ss"));
                        predicateList.add(pre2);

                        Predicate pre3 = cb.le(root.get("createDate").as(Long.class), DateUtils.stringToLong(endDate, "yyyy-MM-dd hh:mm:ss"));
                        predicateList.add(pre3);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }


                if (predicateList.size() > 0) {
                    result = cb.and(predicateList.toArray(new Predicate[]{}));
                }

                if (result != null) {
                    query.where(result);
                }
                return query.getGroupRestriction();
            }

        }, pageRequest);

        return page;
    }

    @Override
    public List<UserInfo> findByStatus() {
        return userInfoDao.findByStatus();
    }

    @Override
    public UserInfo findOneByNickname(String nickname) {
        return userInfoDao.findOneByNickname(nickname);
    }

    @Override
    public List<UserInfo> findListNew() {
        return userInfoDao.findListNew(CommonController.getOldDate());
        //return userInfoDao.findListNew(CommonController.getYesterday().getTime());
    }

    @Override
    @Transactional
    public Integer setCreator(Long userId, Integer status) {
        Creator creator;
        UserInfo userInfo = userInfoDao.findOne(userId);
        if (status == 0) {
            creator = userInfo.getCreator();
            userInfo.setCreator(null);

            List<CreatorDynamic> creatorDynamicList = creatorDynamicDao.findListByCreatorIdPlus(userId);
            for (CreatorDynamic creatorDynamic : creatorDynamicList) {
                creatorDynamicDao.delete(creatorDynamic);
            }

            List<WorkCreator> workCreatorList = workCreatorDao.findByUserId(userId);
            if (workCreatorList.size() != 0) {
                return 2;
            }
        }
        userInfo.setIsCreator(status);

        if (status == 1) {
            creator = new Creator();
            creator.setStatus(0);
            creatorDao.save(creator);
            userInfo.setCreator(creator);

        }

        /*if (StringUtils.isNotEmpty(userInfo.getWeibo()) && StringUtils.isNotEmpty(userInfo.getWeixin()) && StringUtils.isNotEmpty(userInfo.getQq())) {
            UserLogin userLogin = new UserLogin();
            userLogin.setUsername(userInfo.getMobile());
            userLogin.setPassword(userInfo.getPassword());
            userLoginDao.save(userLogin);
            userInfo.setUserLogin(userLogin);
        }*/

        userInfoDao.save(userInfo);
        return 1;

        /*if (status == 0) {
            creatorDao.delete(creator);
        }*/
    }

    @Override
    @Transactional
    public Integer saveUser(String mobile, String nickname, String password, Integer gender, MultipartRequest multipartRequest) throws IOException {
        List<UserInfo> userInfoList = userInfoDao.findAll();
        // 判断昵称是否已存在
        for (UserInfo userInfo1 : userInfoList) {
            if (nickname.equals(userInfo1.getNickname())) {
                return 2;
            }
        }

        // 判断昵称是否包含敏感词
        List<SensitiveWords> wordsList = sensitiveWordsDao.findAll();
        for (SensitiveWords sensitiveWords : wordsList) {
            if (nickname.contains(sensitiveWords.getWords())) {
                return 3;
            }
        }

        // 判断账号是否已存在
        for (UserInfo userInfo1 : userInfoList) {
            if (mobile.equals(userInfo1.getMobile())) {
                return 4;
            }
        }

        UserLogin userLogin = new UserLogin();
        userLogin.setUsername(mobile);
        userLogin.setPassword(password);
        userLoginDao.save(userLogin);

        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(nickname);
        userInfo.setMobile(mobile);
        userInfo.setPassword(password);
        userInfo.setGender(gender);
        userInfo.setUserLogin(userLogin);
        // 类型（0：正常，1：后台添加）
        userInfo.setType(1);
        userInfo.setCreateDate(System.currentTimeMillis());
        MultipartFile multipartFile = multipartRequest.getFile("imageFile");
        if (null != multipartFile) {
            FileBo fileBo = FileUtil.save(multipartFile, true);
            if (fileBo != null) {
                userInfo.setAvater(fileBo.getPath());
                userInfo.setSuolue(fileBo.getSuoluePath());
            }
        }
        userInfoDao.save(userInfo);

        userTaskApiService.setDefaultTask(userInfo.getId());

        return 1;
    }

    @Override
    public List<UserInfo> findList() {
        return userInfoDao.findList();
    }

    @Override
    public List<UserInfo> findByIsCreator(Integer isCreator) {
        return userInfoDao.iFindListByIsCreator(isCreator);
    }
}
